package route

import (
	"net/http"
	"strings"
	"web-app/web-server/internal/constant"
	"web-app/web-server/internal/context"
	"web-app/web-server/internal/dto"
	"web-app/web-server/internal/types"
)

var (
	mapping types.HandlerMapping
)

func Register(handlers []types.WebHandler) {
	mapping = types.NewHandlerMapping(handlers)
}

func WebRoute(ctx *context.Context, resp http.ResponseWriter, req *http.Request) {
	webPath := mapping[req.URL.Path]
	if webPath == nil {
		types.ResultJson(resp, &dto.Result{
			Code:    constant.NotFound,
			Message: "没有找到",
		})
		return
	}
	if strings.ToUpper(req.Method) != strings.ToUpper(webPath.Method) {
		types.ResultJson(resp, &dto.Result{
			Code:    constant.MethodNot,
			Message: "请求方法错误",
		})
		return
	}
	err := webPath.Func(ctx, resp, req)
	if err != nil {
		types.ResultJson(resp, &dto.Result{
			Code:    constant.ServerError,
			Message: "服务器故障",
		})
	}
}
